package com.example.zjx8969.myapplication.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class DotBlinkView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr), LifecycleObserver {
    private val mainScope = MainScope()
    private var job: Job? = null
    private val startAlphas = arrayOf(255, 178, 76)
    val paint = Paint().also {
        it.isAntiAlias = true
        it.style = Paint.Style.FILL
        it.strokeWidth = 4f
    }
    private var radius = 0f
    private var centerPoints = arrayOf(PointF(0f, 0f), PointF(0f, 0f), PointF(0f, 0f))
    private var currentIndex = 0

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let {
            centerPoints.forEachIndexed { index, pointF ->
                val alphaIndex = (currentIndex + index) % 3
                paint.color = Color.argb(startAlphas[alphaIndex], 255, 93, 96)
                it.drawCircle(pointF.x, pointF.y, radius, paint)
            }
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        radius = w / 6f
        val height = h shr 1
        Log.d("tag", "w=$w,h=$h, r = $radius,height = $height")
        centerPoints[0].apply {
            x = radius
            y = height * 1f
        }
        centerPoints[1].apply {
            x = 3 * radius
            y = height * 1f
        }
        centerPoints[2].apply {
            x = 5 * radius
            y = height * 1f
        }

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun startAnimation() {
        if (job?.isActive == true) return
        job = mainScope.launch {
            while (true) {
                delay(500)
                currentIndex = (currentIndex + 1) % 3
                invalidate()

            }
        }

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stopAnimation() {
        job?.cancel()
    }
}